package JavaEE初阶;

import javax.print.attribute.standard.RequestingUserName;
import javax.xml.transform.Source;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{
    //任务队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(4);

    //通过这个方法，把任务添加到队列中
    public void submit(Runnable runnable) throws InterruptedException {
        //此处的拒绝策略是第五种了，直接阻塞等待(下下策)
        queue.put(runnable);
    }

    public MyThreadPool(int n){
        //创建出n个线程，负责执行上述队列中的任务
        for(int i = 0; i < n; i++){
            Thread t = new Thread(() ->{
                //让这个线程从队列中消费任务，并进行执行
                try {
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();

        }
    }
}



public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for(int i = 0 ; i < 1000; i++){
            int id = i;
            myThreadPool.submit(new Runnable(){
                @Override
                public void run(){
                    System.out.println("hello" + id);
                }
            });
        }
    }
}
